﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;

namespace FITClub.Episode1.Configuration
{
    /// <summary>
    /// 
    /// </summary>
    [XmlInclude(typeof(ModelPreset))]
    [XmlRoot(ElementName = "ModelCollector")]   
    public class ModelCollector : List<ModelPreset>
    {
        public const string FILENAME = "Configuration\\ModelCollector.xml";

        private void LoadContent(ContentManager loader)
        {
            this.ForEach((ModelPreset mp) => mp.LoadContent(loader));
        }

        public void SaveXML()
        {
            this.SaveXML(FILENAME);
        }

        /// <summary>
        /// Searches for a ModelPreset by his name.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ModelPreset this[string name]
        {
            get { return this.Single((ModelPreset p) => p.ModelName == name); }
        }

        public static ModelCollector Deserialize(string filename)
        {
#if WINDOWS
            using (Stream input = File.OpenRead(filename))
#else
            using (Stream input = TitleContainer.OpenStream(filename)) 
#endif
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ModelCollector));
                return serializer.Deserialize(input) as ModelCollector;
            }
        }        
        
        /// <summary>
        /// Deserializes XML and loads content.
        /// </summary>
        /// <param name="loader"></param>
        /// <returns></returns>
        public static ModelCollector Load(ContentManager loader)
        {
            ModelCollector mc = Deserialize(FILENAME);
            mc.LoadContent(loader);
            return mc;
        }

        public void SaveXML(string filename)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ModelCollector));
            using (Stream output = File.Open(filename, FileMode.Create, FileAccess.Write))
            {
                serializer.Serialize(output, this);
            }
        }
    }
}
